package com.hamu.interceptors;

import com.hamu.utils.JwtUtil;
import com.hamu.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();

        // 如果请求路径匹配不需要验证令牌的接口
        if (    uri.startsWith("/user/userInfoPublic") ||
                uri.startsWith("/category/all")||
                uri.startsWith("/article/all")||
                uri.startsWith("/article/search")||
                uri.startsWith("/article/detail")||
                uri.startsWith("/media/all")||
                uri.startsWith("/media/search")||
                uri.startsWith("/tag/all")
        ){
            // 不需要令牌验证，直接放行
            return true;
        }

        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try {
            //从redis中获取相同token
            ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if(redisToken==null){
                //token已失效
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存到ThreadLocal中
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        } catch (Exception e) {
            //http 401
            response.setStatus(401);
            return false;
        }

    }
}
